// xc/components/pro/btncart.js
var actcart = require('../../../xc/sys/cart')
Component({
 
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
  
    sumbitbill:{
     type:"string",
     value:"parent"
    },
    clubid:{
      type: Number,
      value: 0
    },
    clubmode:{//指定模式 
      type: Number,
      value: 0
    },
    addrmodel:{
      type: Object,
      value: null
    },
    xcpagesys: {
      type: Object,
      observer(newval, objval) {
        if (newval["foot"]) {
          this.setData({ bottom: newval["foot"]["height"] * 2 + "rpx" })
        }
        else {
          this.setData({ bottom: "0px" })
        }
      }
    },
    unit: {
      type: String,
      value: "￥"
    },
    bottom: {
      type: String,
      value: "50px"
    },
    sumprice: {
      type: Number,
      value: 0,
    },
    selectnum: {
      type: Number,
      value: 0

    },
    themcolor: {
      type: Object,
      value: null
    }
    
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  ready() {

  var that = this;

    setTimeout(() => {
      var app = getApp();
      var pages = getCurrentPages()
      var currentPage = pages[pages.length - 1]
      var actusereg = currentPage.selectComponent("#footer")
      //that.onClickButton()
    }, 1000);

    var that = this;
     
    this.data.Intervalidx= setInterval(function () {
      that.setData({ temtime: Date() })

    }, 1000)
 

    //  this.showcart();
  },

  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
    },
    detached: function() {
      if(this.data.Intervalidx){

        clearInterval(this.data.Intervalidx)
        this.data.Intervalidx=0
      }
       
    },
  },

  methods: {
    onCloseaction() {

      this.setData({ actionsheetshow: false })
      this.triggerEvent("onclosed", {})
    },
    showcart() {
      this.setData({ actionsheetshow: true })
      this.loadcartdata(this.data.clubid);
    },
    toggle() {
      if (this.data.actionsheetshow == true) {
        this.onCloseaction()
      }
      else {
        this.showcart();
      }

    },
     /**判断是否全选 */
     vildchosedall() {
      var noselectnum = 0
      this.data.cartlist.forEach(item => {
        if (item.ischecked == false) {
          noselectnum++
        }
      })

      if (this.data.ischeckedall && noselectnum > 0) {

        this.setData({
          ischeckedall: false
        })
      } else if ((!this.data.ischeckedall) && noselectnum == 0) {

        this.setData({
          ischeckedall: true
        })
      }
    },
    price() {

      var cartlist = this.data.cartlist
      var sumclass = 0
      var sumprice = 0
      var totalnum = 0
      var selectnum = 0;
      for (var a in cartlist) {
        totalnum += cartlist[a].num;
        if (cartlist[a].ischecked) {
          selectnum += cartlist[a].num;
          sumclass++;
          cartlist[a].cid = cartlist[a].cid + "";
          switch (cartlist[a].cid) {
            case "0": {
              sumprice = sumprice + cartlist[a].realprice * cartlist[a].num;
              break;
            }
            case "1": {
              sumprice = sumprice + cartlist[a].activityprice * cartlist[a].num;
              break;
            }
          }
        }
      }

      this.setData({
        sumclass: sumclass,
        sumprice: sumprice,
        totalnum,
        selectnum
      })
    },
    setlimitnum(cartlist) {

      var exinfo = this.data.exinfo;
      // console.log("exinfo")
      if (typeof (exinfo) != 'undefined') {
        var limitcompile = null
        if (exinfo["limitcompile"]) {

          limitcompile = exinfo["limitcompile"];
        } else {

          return cartlist;
        }

        var limitmodel = JSON.parse(JSON.stringify(limitcompile));

        var maxbuy = -1;
        var maxbuypro = -1;
        var limitnum = -1
        if (cartlist) {
          var temitem = null
          for (var a in cartlist) {
            temitem = cartlist[a]
            if (temitem["activityid"]) {
              var activityid = temitem["activityid"];
              var proid = temitem["proid"];
              var actlimitmodel = limitmodel[activityid];

              if (actlimitmodel) {
                var actprolimit = actlimitmodel["prolimit"]
                var maxbuy = parseInt(actlimitmodel["maxbuy"])
                var maxbuypro = parseInt(actlimitmodel["prolimit"][proid])
                var limitnum = maxbuy;
                if (limitnum < 0 || (maxbuypro > 0 && limitnum > maxbuypro)) {
                  limitnum = maxbuypro;
                }
                temitem["limitnum"] = limitnum
                if (limitnum >= 0) {
                  if (temitem["num"] > limitnum) {
                    temitem["num"] = limitnum;
                  }

                }
                if (maxbuypro > 0) {
                  actlimitmodel["prolimit"][proid] -= temitem["num"]
                }
                if (maxbuy > 0) {
                  actlimitmodel["maxbuy"] -= temitem["num"]
                }



              }
            }
          }
        }

        this.setData({
          limitmodel
        })
      }

      
      return cartlist;
    },
    navtopro(e) {
      
      var data = e.currentTarget.dataset
  

      var param = "?id=" + data['id'];
      if (data['activityid']) {
        param += "&activityid=" + data['activityid']
      }
      if (data['cid']) {
        param += "&activitytype=" + data['cid']
      }
      
      wx.navigateTo({
        url: '../pro/proinfo' + param,
      })
    },
    changecartselect(ev) {
      var dataset = ev.currentTarget.dataset
      var idx = dataset.idx
      var item = dataset.item
      actcart.setchk(item.keyval, !item.ischecked)
      var updatemodel = {}
      updatemodel['cartlist[' + idx + '].ischecked'] = !item.ischecked
      this.setData(updatemodel)
      this.price()
      this.vildchosedall()
    },
    numchange(ev) {
      var num = parseInt(ev.detail)
      var dataset = ev.currentTarget.dataset
      var idx = dataset.idx
      var item = dataset.item
      if (num <= 0) {
        num = 0;
      }
      actcart.setnum(item.keyval, num)

      //更新限购
      var cartlist = this.data.cartlist
      cartlist[idx]["num"] = num;
      var cartlist = this.setlimitnum(cartlist);
      if (num == 0) {
        actcart.setnum(cartlist[idx].keyval, 0)

        cartlist.splice(idx, 1);
      }
      // this.setData(cartlist)

      var updatemodel = {};
      updatemodel["cartlist"] = cartlist;
      //更新限购 结束

      this.setData(updatemodel)
      this.price()


    },

    // 全选
    choseall() {
      var ischeckedall = !this.data.ischeckedall
      var cartlist = this.data.cartlist
      for (var a in cartlist) {
        cartlist[a].ischecked = ischeckedall;
      }
      this.setData({
        cartlist: cartlist,
        ischeckedall: ischeckedall
      })

      this.price();

    },
    // 结算 应该用不到
    account() {
      if (this.data.sumclass > 0) {

        app.globalData.temcart = {};
        app.globalData.temcart["cid"] = 1
        app.globalData.temcart["data"] = this.data.cartlist.filter(function (item) {
          return item.ischecked;
        })

        this.clearauto();
        wx.navigateTo({
          url: '../cart/account?iscart=1'
        })
      } else {
        wx.showToast({
          title: '请先选择商品',
          icon: 'none'
        })
      }
    },
    clearcart() {
      var that = this;
      actcart.cleardada().then(function () {
        that.onCloseaction()
      });
    },
    onClickButton() {
      console.log("onClickButton")
      var that = this;
      if (this.data.actionsheetshow) {
        this.loginpay()
      }
      else {
        this.loadcartdata(this.data.clubid).then(function () {

          that.loginpay()
        })

      }
      //loadcartdata


    },
    loginpay() {
      var app = getApp()
      var cartdata = [];    

      this.data.cartlist.forEach(item => {
        if (item.ischecked) {
          if (item.num > 0) {
            cartdata.push(item)
          }
        }
      })
      if (cartdata.length < 1) {

        wx.showToast({
          icon: "error",
          title: '请选择产品',
        })
      } else {

        app.globalData.temcart["data"] = cartdata

        
        
        if(this.data.sumbitbill=="parent"){
       
        var ismust=-1;
        for(var i in cartdata){
         
          if(cartdata[i]['protype'] && cartdata[i]['protype']==2){
            ismust=1
          }
        }
    

          this.triggerEvent("cartsumbit", {"ismust":ismust,"clubmode":this.data.clubmode})
        }
        else
        {
          wx.navigateTo({
            url: '/' + app.globalData.xcsys.m + '/shop/paycore/payinfo?iscart=1'
          })
        }


     
      }

    },
    loadcartdata(clubid) {
      var that = this
    
      return new Promise(function (resolve) {
        actcart.loadcartPromise(clubid).then(function (ret) { 

          if (ret.code == "success") {
            var updatemdoel = {};
            updatemdoel["cartlist"] = ret.data;

            that.data.exinfo = ret["exinfo"]
            updatemdoel["cartlist"] = that.setlimitnum(updatemdoel["cartlist"])

            that.setData(updatemdoel)
            that.price()
            that.vildchosedall()

            resolve({ status: 1 })
          }

        },
          function (e) {
            console.log(e);
          }
        )

      })
    }
  }
})
